/**
 * Created by Jone on 2016/7/14.
 */
var express = require('express');
var router = express.Router();
var Q = require("q");
var mongoose = require('mongoose');
var Group = require('../models/group_model.js').Group;
var Interface = require('../models/interface_model.js').Interface;

/* GET home page. */

router.post('/', function (req, res) {
    console.log('请求参数：' + JSON.stringify(req.body));
    Group.create(req.body, function(err, group){
        if (err) {
            console.log('保存失败');
        } else {
            console.log('保存成功');
            var restult = {code: 0, msg: '保存成功！'};
            res.json(restult);
        }
    });
});

router.put('/', function (req, res) {
    console.log('请求参数：' + JSON.stringify(req.body));
    Group.findByIdAndUpdate(req.body._id, {$set : req.body}, function(err, group){
        if (err) {
            console.log('保存失败');
        } else {
            console.log('保存成功');
            res.json({code: 0, msg: '保存成功！'});
        }
    });
});

router.get('/', function (req, res) {
    console.log('request params:' + JSON.stringify(req.query));
    Group.find({'projectId' : req.query.projectId}, function (err, docs) {
        console.log('user info:' + JSON.stringify(docs));
        res.json({code: 0, msg: 'success', data: docs});
    });
});

router.get('/interfaces', function (req, res) {
    console.log('=====>query params:' + JSON.stringify(req.query));
    Group.find({projectId : req.query.projectId}, function (err, groups) {
        var groupIds = [];
        groups.forEach(function(group) {
            groupIds.push(group._id);
        });
        var groupsDto = [];
        console.log('=====>query groupIds result:' + JSON.stringify(groupIds));
        Interface.find({'groupId' : {$in : groupIds}}, function(err, interfaces){
            groups.forEach(function(group)  {
                var groupDto = group.toObject();
                groupDto.interfaces = [];
                groupsDto.push(groupDto);

                console.log('=====>query interfaces result:' + JSON.stringify(interfaces));

                interfaces.forEach(function(interface) {
                    if(group.id.toString() == interface.groupId.toString()) {
                        groupDto.interfaces.push(interface.toObject());
                    }
                });
            });
            res.json({code: 0, msg: 'success', data: groupsDto});
            console.log('=====>query result:' + JSON.stringify(groupsDto));
        });
    });
});

router.delete('/:id', function (req, res) {
    Group.remove({"_id" : req.params.id}, function (err, docs) {
        console.log('delete info:' + JSON.stringify(docs));
        res.json({code: 0, msg: 'success'});
    });
});


module.exports = router;